package com.website.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.website.common.controller.BaseController;

import com.website.common.factory.ConstantFactory;
import com.website.common.warpper.ResultMap;
import com.website.core.util.DateUtil;
import com.website.core.util.ExcelUtil;
import com.website.core.util.FileUtil;
import com.website.system.model.Computer;

import com.website.system.model.ComputerCategory;
import com.website.system.model.vo.ComputerVO;
import com.website.system.service.ComputerCategoryService;
import com.website.system.service.ComputerService;
import com.website.system.utils.ResponseUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.ui.Model;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("manage/computer")
public class ComputerController extends BaseController {

    @Autowired
    private ComputerService computerService;

    @Autowired
    private ComputerCategoryService computerCategoryService;

    /**
     * 跳转到 后台-->资源管理中心
     */
    @RequestMapping("")
    public String computer() {
        return "manage/computer";
    }

    /**
     * 加载数据 后台-->下载中心管理
     */
    @ApiOperation("下载中心JSON数据")
    @ResponseBody
    @RequestMapping("/computerTable")
    public ResultMap computerTable(@RequestParam(required = false) String title,@RequestParam(required = false) String item,
                                   @RequestParam Integer page, @RequestParam Integer limit) {
        ResultMap<List<ComputerVO>> resultMap = new ResultMap<>(SUCCESS_CODE, SUCCESS_MSG, null, null);
        Wrapper<Computer> wrapper = new EntityWrapper<>();
        Page<Computer> pageInfo = new Page<>(page,limit);
        wrapper = title == null ? wrapper : wrapper.like("title", title).or().like("item", item);
        List<Computer> computer = computerService.selectPage(pageInfo, wrapper.orderBy("created_time", false)).getRecords();
        resultMap.setCount(computerService.selectCount(wrapper));
        List<ComputerVO> voList = new ArrayList<>();  //实例化Vo类
        for (Computer computerList:computer) {
            ComputerVO computerVO =new ComputerVO();
            if(null != computerList.getCategoryId()){
                ComputerCategory computerCategory=computerCategoryService.selectById(computerList.getCategoryId());
                computerVO.setId(computerList.getId());
                computerVO.setCategoryId(computerList.getCategoryId());
                computerVO.setItem(computerList.getItem());
                computerVO.setTitle(computerList.getTitle());
                computerVO.setPoint(computerList.getPoint());
                computerVO.setPrice(computerList.getPrice());
                computerVO.setNum(computerList.getNum());
                computerVO.setPictureUrl(computerList.getPictureUrl());
                computerVO.setPictureId(computerList.getPictureId());
                computerVO.setStatus(computerList.getStatus());
                computerVO.setCreatedTime(computerList.getCreatedTime());
                computerVO.setModifiedTime(computerList.getModifiedTime());
                computerVO.setCreatedUser(ConstantFactory.me().getUserNameById(computerList.getCreatedUser()));
                computerVO.setType(computerCategory.getType());
            }
            voList.add(computerVO);
        }
        resultMap.setData(voList);
        return resultMap;
    }
    /**
     * 加载电脑类别
     */
    @ResponseBody
    @RequestMapping(value = "/computerType", method = RequestMethod.POST)
    public List<ComputerCategory> queryDoctorPosition() {
        Wrapper<ComputerCategory> w = new EntityWrapper<>();
        return computerCategoryService.selectList(w);
    }

    @ResponseBody
    @RequestMapping(value = "/deleteComputer", method = RequestMethod.POST)
    public String deleteDownload(@Param("id")Integer id) {
        try {
             computerService.deleteById(id);
             return SUCCESS_MSG;
        } catch (Exception e) {
             return ERROR_MSG;
        }

    }

    @ResponseBody
    @RequestMapping(value = "/updateComputerStatus", method = RequestMethod.POST)
    public String updateComputerStatus(@Param("id") Integer id, @Param("status") Integer status) {
        try{
            computerService.updateComputerStatus(id, status);
            return SUCCESS_MSG;
        }catch (Exception e){
            return ERROR_MSG;
        }
    }


    @RequestMapping("/toComputerAdd")
    public String toComputerAdd() {
        return "manage/computerAdd";
    }

    /**
     * 添加
     */
    @ResponseBody
    @RequestMapping(value = "/computerAdd",method = RequestMethod.POST)
    public String computerAdd(@ModelAttribute Computer computer) {
        try {
            computer.setCreatedTime(new Date());
            computer.setModifiedTime(new Date());
            computer.setPictureUrl(computer.getPictureId());
            computer.setCreatedUser(getCurrentUser().getId());
            computer.setStatus(SHOW_STATE);
            computerService.insert(computer);
            return SUCCESS_MSG;
        }catch (Exception e){
            return ERROR_MSG;
        }
    }

    @RequestMapping(value = "/toComputerUpdate/{id}", method = RequestMethod.GET)
    public String computerUpdateId(Model model, @PathVariable("id") Integer id, HttpServletRequest request) {
         Computer computer=computerService.selectById(id);
         request.setAttribute("computer",computer);
         request.setAttribute("id",id);
          model.addAttribute(computer);
        return "manage/computerUpdate";
    }

    @ResponseBody
    @RequestMapping(value = "/computerUpdate",method = RequestMethod.POST)
    public String computerUpdate(@ModelAttribute Computer computer) {
        try {
            Computer oldPicture = computerService.selectById(computer.getId());
            // 判断图片的id有没有变动；变动的话，就删除原来的图片
            if(!oldPicture.getPictureId().equals(computer.getPictureId())){
                deleteFile(oldPicture.getPictureUrl());
                computer.setPictureUrl(computer.getPictureId());
            }
            computer.setStatus(SHOW_STATE);
            computer.setModifiedTime(new Date());
            computerService.updateById(computer);
            return SUCCESS_MSG;
        }catch (Exception e){
            return ERROR_MSG;
        }

    }
    @RequestMapping("/excel_down")
    public String excel_down(HttpServletResponse response,HttpServletRequest request) throws Exception {
       String webPath=request.getServletContext().getRealPath("/");
       Wrapper<Computer> w = new EntityWrapper<>();
       List<Computer> list=computerService.selectList(w);
        Workbook wb = fillExcelDataWithTemplate(list, webPath+"/static/client_down_model.xls");
        ResponseUtil.export(response,wb,"电脑.xls");

        return  null;

    }
    /**
     * @param templateFileUrl
     *            excel模板的路径 /admin/page/JYZ/client/client_info.xls
     * @return
     */
    public static Workbook fillExcelDataWithTemplate(List<Computer> list ,String templateFileUrl) {

        Workbook wb = null ;
        try {
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(templateFileUrl));
            wb = new HSSFWorkbook(fs);
            // 取得 模板的 第一个sheet 页
            Sheet sheet = wb.getSheetAt(0);
            // 拿到sheet页有 多少列
            //int cellNums = sheet.getRow(0).getLastCellNum();
            // 从第2行 开搞    下标1  就是第2行
            int rowIndex = 1;
            Row row ;
            for(Computer computer : list){
                row = sheet.createRow(rowIndex);
                rowIndex ++;

                row.createCell(0).setCellValue(computer.getId());
                row.createCell(1).setCellValue(computer.getCategoryId());
                row.createCell(2).setCellValue(computer.getItem());
                row.createCell(3).setCellValue(computer.getTitle());
                row.createCell(4).setCellValue(computer.getPoint());
                row.createCell(5).setCellValue(computer.getPrice());
                row.createCell(6).setCellValue(computer.getNum());
                row.createCell(7).setCellValue(computer.getPictureUrl());
                row.createCell(8).setCellValue(computer.getStatus());
                row.createCell(9).setCellValue(computer.getCreatedUser());
                row.createCell(10).setCellValue(DateUtil.formatDate(computer.getCreatedTime(), "yyyy-MM-dd HH:mm:ss"));
                row.createCell(11).setCellValue(DateUtil.formatDate(computer.getModifiedTime(), "yyyy-MM-dd HH:mm:ss"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }
    @ResponseBody
    @RequestMapping("/upload_excel")
    public JSONObject upload_excel(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request)throws Exception {
        JSONObject result = new JSONObject();
        if(!file.isEmpty()){
            String webPath=request.getServletContext().getRealPath("");
            String filePath= "/static/upload_file/excel/";
            //把文件名子换成（时间搓.png）
            String fileName=DateUtil.formatDate(new Date(), "yyyyMMdd-HHmmssSSS")+"_"+file.getOriginalFilename();
            FileUtil.makeDirs(webPath+filePath);
            //保存服务器
            file.transferTo(new File(webPath+filePath+fileName));
            //解析
            List<Computer> list =  excel_to_clientInfo(new File(webPath+filePath+fileName));
            //开始 上传 数据库
            for(Computer computer:list) {
                computerService.insert(computer);
            }
            //删除用过的文件
            FileUtil.deleteFile(webPath+filePath+fileName);
            //删除用过的文件
        }
        result.put("success", true);
        result.put("msg", "导入成功");
        return result;
    }

    private List<Computer> excel_to_clientInfo(File userUploadFile) throws ParseException {
        List<Computer> list = new ArrayList<Computer>();
        Computer computer = null;
        try {
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(userUploadFile));
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            //获取第一个sheet页
            HSSFSheet sheet = wb.getSheetAt(0);
            if(sheet!=null){
                for(int rowNum =1;rowNum<=sheet.getLastRowNum();rowNum++){
                    HSSFRow row = sheet.getRow(rowNum);
                    if(row==null){
                        continue;
                    }
                    computer  =new Computer();
                    computer.setId(Integer.parseInt(ExcelUtil.formatCell(row.getCell(0)).substring(0,ExcelUtil.formatCell(row.getCell(0)).lastIndexOf("."))));
                    computer.setCategoryId(Integer.parseInt(ExcelUtil.formatCell(row.getCell(1)).substring(0,ExcelUtil.formatCell(row.getCell(1)).lastIndexOf("."))));
                    computer.setItem(ExcelUtil.formatCell(row.getCell(2)));
                    computer.setTitle(ExcelUtil.formatCell(row.getCell(3)));
                    computer.setPoint(ExcelUtil.formatCell(row.getCell(4)));
                    computer.setPrice(Integer.parseInt(ExcelUtil.formatCell(row.getCell(5)).substring(0,ExcelUtil.formatCell(row.getCell(5)).lastIndexOf("."))));
                    computer.setNum(Integer.parseInt(ExcelUtil.formatCell(row.getCell(6)).substring(0,ExcelUtil.formatCell(row.getCell(6)).lastIndexOf("."))));
                    computer.setPictureUrl(ExcelUtil.formatCell(row.getCell(7)));
                    computer.setStatus(Integer.parseInt(ExcelUtil.formatCell(row.getCell(8)).substring(0,ExcelUtil.formatCell(row.getCell(8)).lastIndexOf("."))));
                    computer.setCreatedUser(Integer.parseInt(ExcelUtil.formatCell(row.getCell(9)).substring(0,ExcelUtil.formatCell(row.getCell(9)).lastIndexOf("."))));
                    computer.setCreatedTime(ExcelUtil.formatDate(row.getCell(10)));
                    computer.setModifiedTime(ExcelUtil.formatDate(row.getCell(11)));
                    list.add(computer);
                }
            }
        }  catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }


}
